import React, { useState, useEffect, useRef } from 'react';
import {
  Table,
  Form,
  Select,
  DatePicker,
  Button,
  Space,
  Card,
  Row,
  Col,
  Popover,
  Checkbox,
  Pagination,
  Tag,
  message
} from 'antd';
import {
  SearchOutlined,
  FilterOutlined,
  ReloadOutlined,
  PlusOutlined,
  EyeOutlined,
  EditOutlined,
  CopyOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import {
  getCardList,
  getCardTypes,
  getCardFormFactors,
  getCardStatus,
  type CardItem,
  type CardTypeOption,
  type CardFormFactorOption,
  type CardStatusOption,
  type CardListRequest
} from '@/api/modules/card';
import CreateBankCard, { type CreateBankCardRef } from './list/components/CreateBankCard';
import EditNickname, { type EditNicknameRef } from './list/components/EditNickname';
import CardTransferAmount, { type CardTransferAmountRef } from './list/components/CardTransferAmount';

const { RangePicker } = DatePicker;
const { Option } = Select;

/**
 * 查询数据接口
 * 定义卡片列表查询参数
 */
interface QueryData {
  time: [dayjs.Dayjs, dayjs.Dayjs] | null; // 时间范围
  cardType: string; // 卡片类型
  cardFormFactor: string; // 卡片介质
  cardStatus: string; // 卡片状态
}

/**
 * 卡片列表组件
 * 用于展示和管理卡片列表，包括查询、筛选、分页、创建、编辑等功能
 */
const CardList: React.FC = () => {
  const navigate = useNavigate(); // 路由导航
  const [loading, setLoading] = useState(false); // 加载状态
  const [queryFormOpen, setQueryFormOpen] = useState(true); // 查询表单显示状态
  const [queryData, setQueryData] = useState<QueryData>({
    time: null, // 时间范围
    cardType: '', // 卡片类型
    cardFormFactor: '', // 卡片介质
    cardStatus: '' // 卡片状态
  });
  const [tableQuery, setTableQuery] = useState({
    page: 1, // 当前页码
    perPage: 20 // 每页条数
  });
  const [tableTotal, setTableTotal] = useState(0); // 总数据条数
  const [tableList, setTableList] = useState<CardItem[]>([]); // 表格数据
  const [cardTypes, setCardTypes] = useState<CardTypeOption[]>([]); // 卡片类型选项
  const [cardFormFactors, setCardFormFactors] = useState<CardFormFactorOption[]>([]); // 卡片介质选项
  const [cardStatusList, setCardStatusList] = useState<CardStatusOption[]>([]); // 卡片状态选项
  const [screenList, setScreenList] = useState<Array<{
    label: string; // 列标签
    prop: string; // 数据属性
    align: 'center' | 'left' | 'right'; // 对齐方式
    disabled: boolean; // 是否禁用
    show: boolean; // 是否显示
    minWidth: string; // 最小宽度
  }>>([]); // 表格列筛选配置

  // 引用模态框组件
  const createBankCardRef = useRef<CreateBankCardRef>(null); // 创建银行卡引用
  const editNicknameRef = useRef<EditNicknameRef>(null); // 编辑昵称引用
  const cardTransferAmountRef = useRef<CardTransferAmountRef>(null); // 卡片转账引用

  /**
   * 初始化表格列配置
   * 设置表格列的显示、对齐、宽度等属性
   */
  const initScreenList = () => {
    const columns = [
      {
        label: '开卡时间',
        prop: 'created_at',
        align: 'center' as const,
        disabled: false,
        show: true,
        minWidth: '180'
      },
      {
        label: '卡ID',
        prop: 'card_json.cardId',
        align: 'center' as const,
        disabled: false,
        show: true,
        minWidth: '200'
      },
      {
        label: '卡号',
        prop: 'card_json.maskCardNo',
        align: 'center' as const,
        disabled: false,
        show: true,
        minWidth: '210'
      },
      {
        label: '持卡人',
        prop: 'cardholder',
        align: 'center' as const,
        disabled: false,
        show: true,
        minWidth: '160'
      },
      {
        label: '邮箱',
        prop: 'card_json.email',
        align: 'center' as const,
        disabled: false,
        show: true,
        minWidth: '180'
      },
      {
        label: '卡介质',
        prop: 'cardFormFactor',
        align: 'center' as const,
        disabled: false,
        show: true,
        minWidth: '80'
      },
      {
        label: '卡类型',
        prop: 'cardType',
        align: 'center' as const,
        disabled: false,
        show: true,
        minWidth: '80'
      },
      {
        label: '昵称',
        prop: 'nickname',
        align: 'center' as const,
        disabled: false,
        show: true,
        minWidth: '160'
      },
      {
        label: '余额',
        prop: 'cardBalance',
        align: 'center' as const,
        disabled: false,
        show: true,
        minWidth: '160'
      },
      {
        label: '状态',
        prop: 'cardStatus',
        align: 'center' as const,
        disabled: false,
        show: true,
        minWidth: '100'
      }
    ];
    setScreenList(columns);
  };

  /**
   * 获取数据列表
   * 根据查询条件从API获取卡片列表数据
   */
  const getDataList = async () => {
    setLoading(true); // 开始加载
    try {
      const params: CardListRequest = {
        _action: 'getData',
        page: tableQuery.page, // 当前页码
        perPage: tableQuery.perPage, // 每页条数
        cardType: queryData.cardType || undefined, // 卡片类型
        cardFormFactor: queryData.cardFormFactor || undefined, // 卡片介质
        cardStatus: queryData.cardStatus || undefined // 卡片状态
      };

      // 如果有时间范围，添加到参数中
      if (queryData.time) {
        params.createdAtStart = queryData.time[0].format('YYYY-MM-DDTHH:mm:ss');
        params.createdAtEnd = queryData.time[1].format('YYYY-MM-DDTHH:mm:ss');
      }

      const response = await getCardList(params);
      setTableList(response.data.items); // 设置表格数据
      setTableTotal(response.data.total); // 设置总数据条数
    } catch (error) {
      console.error('获取数据失败:', error);
      message.error('获取数据失败');
    } finally {
      setLoading(false); // 结束加载
    }
  };

  /**
   * 获取选项数据
   * 获取卡片类型、介质、状态等选项数据
   */
  const getOptionsData = async () => {
    try {
      // 并行获取所有选项数据
      const [typesRes, factorsRes, statusRes] = await Promise.all([
        getCardTypes(), // 卡片类型
        getCardFormFactors(), // 卡片介质
        getCardStatus() // 卡片状态
      ]);

      // 响应拦截器已经返回了数据数组，直接使用
      setCardTypes(Array.isArray(typesRes) ? typesRes : []);
      setCardFormFactors(Array.isArray(factorsRes) ? factorsRes : []);
      setCardStatusList(Array.isArray(statusRes) ? statusRes : []);
    } catch (error) {
      console.error('获取选项数据失败:', error);
      // 设置空数组以防错误
      setCardTypes([]);
      setCardFormFactors([]);
      setCardStatusList([]);
    }
  };

  /**
   * 重置查询表单
   * 清空所有查询条件并重新获取数据
   */
  const queryFormReset = () => {
    setQueryData({
      time: null,
      cardType: '',
      cardFormFactor: '',
      cardStatus: ''
    });
    setTableQuery(prev => ({ ...prev, page: 1 })); // 重置到第一页
    getDataList(); // 重新获取数据
  };

  /**
   * 复制文本到剪贴板
   * @param text 要复制的文本
   */
  const copyText = (text: string) => {
    navigator.clipboard.writeText(text).then(() => {
      message.success('复制成功');
    }).catch(() => {
      message.error('复制失败');
    });
  };

  /**
   * 表格列配置
   * 根据筛选配置生成表格列
   */
  const columns: ColumnsType<CardItem> = screenList
    .filter(item => item.show) // 只显示启用的列
    .map(item => {
      const column: {
        title: string;
        dataIndex: string;
        key: string;
        align: 'center' | 'left' | 'right';
        width?: string | number;
        render?: (value: unknown, record: CardItem) => React.ReactNode;
      } = {
        title: item.label, // 列标题
        dataIndex: item.prop, // 数据属性
        key: item.prop, // 唯一键
        align: item.align, // 对齐方式
        width: item.minWidth, // 宽度
        render: (value: unknown, record: CardItem): React.ReactNode => {
          switch (item.prop) {
            case 'card_json.maskCardNo':
              // 卡号列：显示掩码卡号和复制图标
              return (
                <Space>
                  {/* 这里需要根据卡组织显示图标 */}
                  <span>{record.card_json.maskCardNo}</span>
                  <CopyOutlined
                    style={{ color: '#1890ff', cursor: 'pointer' }}
                    onClick={() => copyText(record.card_json.cardNo)} // 复制完整卡号
                  />
                </Space>
              );
            case 'cardholder':
              // 持卡人列：拼接姓名
              return `${record.card_json.firstName} ${record.card_json.lastName}`;
            case 'cardFormFactor':
              // 卡介质列：查找对应的标签
              return cardFormFactors.find(f => f.value === record.card_json.cardFormFactor)?.label || record.card_json.cardFormFactor;
            case 'cardType':
              // 卡类型列：查找对应的标签
              return cardTypes.find(t => t.value === record.card_json.cardType)?.label || record.card_json.cardType;
            case 'nickname':
              // 昵称列：显示昵称和编辑图标
              return (
                <Space>
                  <span>{record.card_json.nickname || '-'}</span>
                  <EditOutlined
                    style={{ cursor: 'pointer' }}
                    onClick={() => editNicknameRef.current?.show(record.id, record.card_json.nickname)} // 打开编辑模态框
                  />
                </Space>
              );
            case 'cardBalance':
              // 余额列：显示余额和货币
              return (
                <Space>
                  <span className="font-bold">{record.card_json.cardBalance}</span>
                  <span>{record.card_json.cardCurrency}</span>
                  {/* 这里需要显示货币图标 */}
                </Space>
              );
            case 'cardStatus':
              // 状态列：根据状态显示不同颜色的标签
              return (() => {
                const statusItem = cardStatusList.find(s => s.value === record.card_json.cardStatus);
                return (
                  <Tag color={statusItem?.type === 'success' ? 'green' : statusItem?.type === 'danger' ? 'red' : 'default'}>
                    {statusItem?.label || record.card_json.cardStatus}
                  </Tag>
                );
              })();
            default:
              // 默认列：直接显示值
              return value as React.ReactNode;
          }
        }
      };

      return column;
    });

  // 操作列配置
  const operationColumn: ColumnsType<CardItem> = [
    {
      title: '操作',
      key: 'operation',
      align: 'center' as const,
      fixed: 'right' as const,
      width: 120,
      render: (_, record) => (
        <Space>
          {/* 查看详情按钮 */}
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => navigate(`/card_manage/detail?id=${record.id}`)} // 跳转到详情页
          >
            查看详情
          </Button>
          {/* 只有正常状态的卡片显示转入按钮 */}
          {record.card_json.cardStatus === 'normal' && (
            <Button
              type="link"
              size="small"
              onClick={() => cardTransferAmountRef.current?.show(
                record.id,
                record.card_json.maskCardNo,
                record.card_json.cardBalance,
                record.card_json.cardCurrency
              )} // 打开转账模态框
            >
              转入
            </Button>
          )}
        </Space>
      )
    }
  ];

  // useEffect钩子：组件挂载时初始化列配置和获取选项数据
  useEffect(() => {
    initScreenList();
    getOptionsData();
  }, []);

  // useEffect钩子：当分页参数变化时重新获取数据
  useEffect(() => {
    getDataList();
  }, [tableQuery.page, tableQuery.perPage]);

  // 合并所有列配置
  const finalColumns = [...columns, ...operationColumn];

  return (
    <div className="p-6">
      <Card className="m-0 px-6 shadow-[0px_0px_16px_0px_rgba(0,0,0,0.03)]">
        {/* 查询表单 */}
        {queryFormOpen && (
          <Form
            layout="vertical"
            className="query-form"
            onFinish={getDataList}
          >
            <Row gutter={[50, 16]} justify="space-between">
              <Col xl={8} lg={8} md={12} sm={24} xs={24}>
                <Form.Item label="开卡时间">
                  <RangePicker
                    value={queryData.time}
                    onChange={(dates) => setQueryData(prev => ({ ...prev, time: dates as [dayjs.Dayjs, dayjs.Dayjs] }))}
                    showTime
                    style={{ width: '100%' }}
                  />
                </Form.Item>
              </Col>
              <Col xl={6} lg={8} md={12} sm={24} xs={24}>
                <Form.Item label="卡类型">
                  <Select
                    value={queryData.cardType}
                    onChange={(value) => setQueryData(prev => ({ ...prev, cardType: value }))}
                    placeholder="请选择卡类型"
                    allowClear
                  >
                    {cardTypes.map(item => (
                      <Option key={item.value} value={item.value}>
                        {item.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col xl={6} lg={8} md={12} sm={24} xs={24}>
                <Form.Item label="卡介质">
                  <Select
                    value={queryData.cardFormFactor}
                    onChange={(value) => setQueryData(prev => ({ ...prev, cardFormFactor: value }))}
                    placeholder="请选择卡介质"
                    allowClear
                  >
                    {cardFormFactors.map(item => (
                      <Option key={item.value} value={item.value}>
                        {item.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col xl={6} lg={8} md={12} sm={24} xs={24}>
                <Form.Item label="卡状态">
                  <Select
                    value={queryData.cardStatus}
                    onChange={(value) => setQueryData(prev => ({ ...prev, cardStatus: value }))}
                    placeholder="请选择卡状态"
                    allowClear
                  >
                    {cardStatusList.map(item => (
                      <Option key={item.value} value={item.value}>
                        {item.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col xl={6} lg={8} md={12} sm={24} xs={24}>
                <Form.Item label=" ">
                  <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
                    <Button onClick={queryFormReset}>
                      重置
                    </Button>
                    <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                      查询
                    </Button>
                  </Space>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        )}

        {/* 工具栏 */}
        <div className={`table-toolbar transition-all ${queryFormOpen ? 'mt-4' : ''}`}>
          <Space>
            {/* 筛选显示列 */}
            <Popover
              content={
                <div>
                  {screenList.map((item, index) => (
                    <div key={index}>
                      <Checkbox
                        checked={item.show}
                        disabled={item.disabled}
                        onChange={(e) => {
                          const newList = [...screenList];
                          newList[index].show = e.target.checked;
                          setScreenList(newList);
                        }}
                      >
                        {item.label}
                      </Checkbox>
                    </div>
                  ))}
                </div>
              }
              trigger="click"
            >
              <Button icon={<FilterOutlined />} />
            </Popover>

            {/* 新增银行卡 */}
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={() => createBankCardRef.current?.show()}
            >
              创建新的卡片
            </Button>

            {/* 刷新 */}
            <Button 
              icon={<ReloadOutlined />}
              onClick={getDataList}
            />

            {/* 筛选 */}
            <Button 
              type="primary" 
              icon={<FilterOutlined />}
              onClick={() => setQueryFormOpen(!queryFormOpen)}
            >
              筛选
            </Button>
          </Space>
        </div>

        {/* 表格 */}
        <Table
          loading={loading}
          columns={finalColumns}
          dataSource={tableList}
          rowKey="id"
          pagination={false}
          scroll={{ x: 1500 }}
          className="mt-4"
        />

        {/* 分页 */}
        <div className="mt-3" style={{ textAlign: 'right' }}>
          <Pagination
            current={tableQuery.page}
            pageSize={tableQuery.perPage}
            total={tableTotal}
            showSizeChanger
            pageSizeOptions={['20', '50', '100', '200', '400']}
            showTotal={(total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`}
            onChange={(page, pageSize) => setTableQuery({ page, perPage: pageSize })}
          />
        </div>
      </Card>

      {/* 模态框组件 */}
      <CreateBankCard ref={createBankCardRef} onRefresh={getDataList} />
      <EditNickname ref={editNicknameRef} onRefresh={getDataList} />
      <CardTransferAmount ref={cardTransferAmountRef} onRefresh={getDataList} />
    </div>
  );
};

export default CardList;